package com.hjl.cn.config.api;

import com.alibaba.fastjson.JSONObject;
import com.hjl.cn.utils.RedisUtils;
import com.hjl.cn.vo.UsersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author jialin
 * @createTime 2020-09-14
 */
public class LoginRequiredComplete implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //只要添加了注解就获取到整个方法
        Method method = handlerMethod.getMethod();
        LoginRequired annotation = method.getAnnotation(LoginRequired.class);
        //判断是否添加了注解
        if (null != annotation) {
            String token = null;
            String wxToken = httpServletRequest.getHeader("wxToken");
            String ptToken = httpServletRequest.getHeader("token");
            if (StringUtils.isEmpty(wxToken)) {
                token = ptToken;
            }else if (StringUtils.isEmpty(ptToken)){
                token = wxToken;
            }
            if (StringUtils.isEmpty(token)) {
                throw new RuntimeException("login error");
            }
            Object obj = redisUtils.get(token);
            if (ObjectUtils.isEmpty(obj)) {
                throw new RuntimeException("token error");
            }
            /*//token超时
            if (redisUtils.getExpire(token) < 0) {
                throw new RuntimeException("token over time");
            }*/
            UsersVo usersVo = JSONObject.parseObject(obj.toString(), UsersVo.class);
            httpServletRequest.setAttribute("loginUserVo",usersVo);
            //重新设置超时时间
            redisUtils.expire(token, 7200);
            return true;
        }
        return true;
    }

    public static void main(String[] args) {
        Integer a = 1000, b = 1000;
        System.out.println(a == b);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
